import { defineStore } from 'pinia'
import {
  apiArcSearch,
  apiArcInfo,
  apiSeasonsSeriesList,
  apiSpaceUpstat,
  apiSeasonsArchivesList
} from '@renderer/api/bilibili'
import axios from 'axios'
import router from '@renderer/router'
import { storageLocal } from '@renderer/tools/index'

import type { ApiArcSearchParams } from '@renderer/api/bilibili'
import type { ArtistInfo, TrackInfo } from '@renderer/views/track/type'

interface State {
  default: number
}

export const useSearchStore = defineStore('search', {
  state: (): State => ({
    default: 0
  }),
  getters: {},
  actions: {
    async test(mid: number) {
      const vlist = await this.getUserVideoInfo(mid)
      const tracks: TrackInfo[] = vlist.map((item) => {
        const duraSplit = item.length.split(':')
        const duration = duraSplit[0] * 60 + duraSplit[1] * 1
        const cover = item.pic.replace(/^http:/i, 'https:')
        return {
          avid: item.aid,
          bvid: item.bvid,
          cid: 0,
          cover,
          title: item.title,
          author: item.author,
          authorid: mid,
          duration,
          description: item.description,
          pubdate: item.created // 发布日期
        }
      })
      const userInfo = await this.getUserInfo(mid)
      if (userInfo) {
        const { name, face, sign } = userInfo
        // const params: ArtistInfo = {
        const params: any = {
          id: mid,
          cover: face,
          name,
          description: sign,
          songcount: tracks.length,
          tracks,
          type: 2
        }
        storageLocal().setItem('track-list', params)
        router.push({ name: 'track-list' })
      }
    },
    async test1(mid: number) {
      const userInfo = await this.getUserInfo(mid)
      const upstat = await this.getUpstat(mid)
      const seasons = await this.getSeasons(mid)
      const albums = seasons.map(({ meta }) => ({
        id: meta.season_id,
        title: meta.name,
        total: meta.total,
        cover: meta.cover
      }))
      if (userInfo && upstat) {
        const { name, face, sign } = userInfo
        const params: ArtistInfo | any = {
          id: mid,
          cover: face,
          name,
          description: sign,
          songcount: 0,
          tracks: [],
          type: 2,
          ...upstat,
          albums
        }
        storageLocal().setItem('track-list', params)
        router.push({ name: 'track-list' })
      }
    },
    async getUserVideoInfo(mid: number): Promise<any[]> {
      const params: ApiArcSearchParams = {
        mid,
        tid: 3
      }
      const { data, code } = await apiArcSearch(params)
      if (code === 0) {
        return data.list.vlist
      }
      return []
    },
    async getUserInfo(mid: number): Promise<Record<string, any> | null> {
      const webid = await getWebid(mid)
      if (webid) {
        const { data, code } = await apiArcInfo({
          mid,
          w_webid: webid
        })
        if (code === 0) {
          return data
        }
      }
      return null
    },
    async getSeasons(mid: number): Promise<any[]> {
      const webid = await getWebid(mid)
      if (webid) {
        const params = {
          mid,
          w_webid: webid,
          page_num: 1,
          page_size: 20
        }
        const { data, code } = await apiSeasonsSeriesList(params)
        if (code === 0) {
          return data.items_lists.seasons_list
        }
      }
      return []
    },
    async getUpstat(mid: number): Promise<{ likes: number; view: number } | null> {
      const { data, code } = await apiSpaceUpstat({ mid })
      if (code === 0) {
        return {
          likes: data.likes,
          view: data.archive.view
        }
      }
      return null
    },
    async getSeasonVideoInfo(mid: number, season_id: number): Promise<any[]> {
      const { data, code } = await apiSeasonsArchivesList({
        mid,
        season_id,
        page_num: 1,
        page_size: 30
      })
      if (code === 0) {
        return data.archives
      }
      return []
    }
  }
})

const webidMap = new Map<number, string>()

async function getWebid(mid: number): Promise<string | null> {
  if (webidMap.has(mid)) {
    return webidMap.get(mid)!
  }
  const response = await axios.get('https://space.bilibili.com/' + mid)
  const reg = /<script id="__RENDER_DATA__" type="application\/json">(.*?)<\/script>/
  const match: RegExpExecArray | null = reg.exec(response.data)
  if (match) {
    const data = JSON.parse(decodeURIComponent(match[1]))
    webidMap.set(mid, data.access_id)
    return data.access_id
  }
  return null
}
